<!--
 * @Author: wway 951357249@qq.com
 * @Date: 2023-11-23 22:25:41
 * @LastEditors: wway 951357249@qq.com
 * @LastEditTime: 2023-11-24 17:24:16
 * @FilePath: \vite-project\src\components\forn\index.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<style lang="scss" scoped></style>
<template>
    <Form ref="formDynamic" :model="formDynamic" :label-width="80" style="width: 300px">
        <template v-for="(item, index) in formDynamic.items">
            <FormItem v-if="item.status" :key="index" :label="'Item ' + item.index" :prop="'items.' + index + '.value'"
                :rules="{ required: true, message: 'Item ' + item.index + ' can not be empty', trigger: 'blur' }">
                <Row>
                    <Col span="18">
                    <Input type="text" v-model="item.value" placeholder="Enter something..."></Input>
                    </Col>
                    <Col span="4" offset="1">
                    <Button @click="handleRemove(index)">Delete</Button>
                    </Col>
                </Row>
            </FormItem>
        </template>
        <FormItem>
            <Row>
                <Col span="12">
                <Button type="dashed" long @click="handleAdd" icon="md-add">Add item </Button>
                </Col>
            </Row>
        </FormItem>
        <FormItem>
            <Button type="primary" @click="handleSubmit('formDynamic')">Submit </Button>
            <Button @click="handleReset('formDynamic')" style="margin-left: 8px">Reset</Button>
        </FormItem>
    </Form>
</template>

<script lang="ts" >
 export default {
        data () {
            return {
                index: 1,
                formDynamic: {
                    items: [
                        {
                            value: '',
                            index: 1,
                            status: 1
                        }
                    ]
                }
            }
        },
        methods: {
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Message.success('Success!');
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            handleAdd () {
                this.index++;
                this.formDynamic.items.push({
                    value: '',
                    index: this.index,
                    status: 1
                });
            },
            handleRemove (index) {
                this.formDynamic.items[index].status = 0;
            }
        }
    }
</script>